/*
 * 对文件进行切片上传，支持断点续传
 */
var file;
var fileInput = document.querySelector('#fileInput');
var progressText = document.querySelector('#progress-text');
var sliceList = [];
var urlList = [];
var etagList = [];
var retryTimes = 3;
var failedList = [];
var successIndex = 0; //当前上传成功的切片数目
var isInterrupted = false; //判断是否上传中断，用来模拟文件上传中断
var successFileList=[];//上传成功的文件分片名称

fileInput.addEventListener("change", function() {
	file = this.files[0];
	progressText.innerText = "0/0";
    successFileList = [];
});

function downloadFile(){
	if(successFileList.length==0){
		alert("文件未上传成功，无法下载！");
	}else{
        var fileBlocks = "";
        for (var i = 0; i < successFileList.length; i++) {
            if (i > 0) {
                fileBlocks = fileBlocks + ";";
            }
            fileBlocks = fileBlocks + successFileList[i];
        }
        window.location.href = "/xstore-s3-demo/file/download?file=" + file.name + "&fileBlocks=" + fileBlocks;
    }
}

function uploadFile() {
	failedList = [];
	successIndex = 0;
    successFileList = [];
    isInterrupted = false;
    var sendType = $("input[name='sendType']:checked").val();
    //如果是分片上传，partSize用分片的大小，否则用整个文件的大小
    partSize = sendType == "1" ? 2 * 1024 * 1024 : file.size;
    var params = {
        file: file.name,
        fileSize: file.size,
        partSize: partSize
    };

    ajax({
        url: "/xstore-s3-demo/s3/presignRequest",
        type: "Get",
        contentType: "application/json",
        data: params,
        dataType: "json",
        success: function(response) {
            var res = JSON.parse(response);
            urlList = res;
            progressText.innerText = "0/" + urlList.length;
            sliceList = sliceFile(file, urlList.length, params.partSize);//切割文件
            sendFileSlice(sliceList, urlList);//上传文件切片
        },
        error: function(status) {

        }
    });
}

function interruptSendFile(){
    alert("do interruptSendFile");
    isInterrupted = true;
}

function continueSendFile(){
    alert("continueSendFile");
    isInterrupted = false;
    sendFileSlice(sliceList, urlList);
}

function sendFileSlice(sliceList, urlList) {
	if(isInterrupted){
		return;
	}
	var len = sliceList.length;
	ajax({
		url: urlList[successIndex]["url"],
		type: "put",
		contentType: "binary/octet-stream",
		data: sliceList[successIndex],
		dataType: "json",
		header:{'x-amz-grant-read':'uri="http://acs.amazonaws.com/groups/global/AllUsers"'},//设置文件的访问权限：所有用户都可以读取
		success: function(responseText, etag) {
			etagList.push({
				partNumber: successIndex + 1,
				eTag: etag.replace(/\"/g, "")
			});
			console.log(etagList);
			successIndex = successIndex + 1;
			progressText.innerText = successIndex + "/" + len;

			if(successIndex < len) {
				sleep(5000);
				sendFileSlice(sliceList, urlList);
			}else if(successIndex  == len) {//文件上传完成
                successIndex = 0;
				etagList = [];
                for (var i = 0; i < urlList.length; i++) {
                    successFileList.push( urlList[i]["key"]);//保存文件切片的名称
                }
                alert("文件上传完成");
			}
		},
		error: function(status) {
			//重传机制
			if(failedList.length == 0 || failedList[failedList.length - 1].partNumer != successIndex) {
				var failedObj = {
					partNumber: successIndex,
					retry: 0
				};
				failedList.push(failedObj);
			}
			var retryObj = failedList[failedList.length - 1];
			if(retryObj.retry < retryTimes) {
				retryObj.retry++;
				sendFileSlice(sliceList, urlList);
			} else{
			    alert("文件上传失败，请重新上传");
            }
		}
	});
}

function sliceFile(file, sliceNum, sliceSize) {
	var sliceList = [];
	var start = 0;
	var end = file.size;
	for(var i = 0; i < sliceNum; i++) {
		var slicePoint = Math.min(start + sliceSize, end);
		sliceList[i] = file.slice(start, slicePoint);
		start = start + sliceSize;
	}
	return sliceList;
}

function changeType(val){
    if (val == 2) {
        $("#btnInterrupt").hide();
        $("#btnContinue").hide();
    } else if (val == 1) {
        $("#btnInterrupt").show();
        $("#btnContinue").show();
    }
}

/**
 * 休眠
 * @param time 单位毫秒
 */
function sleep(time) {
    var startTime = new Date().getTime() + parseInt(time, 10);
    while (new Date().getTime() < startTime) {

    }
}